<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/14
 * Time: 11:21
 */
namespace App\Service\Api;

use App\Http\Model\MongoDB\LiveList;
use App\Http\Model\Mysql\BoxModel;
use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\UserModel;
use App\Http\Model\Mysql\WechatOrderModel;
use App\Http\Model\Mysql\ProductModel;
use App\Http\Model\Mysql\ProductGiftModel;
use App\Http\Model\Mysql\CouponModel;
use App\Http\Model\Mysql\CouponConnectionModel;
use App\Http\Model\Mysql\UserCouponModel;
use App\Http\Model\Mysql\UserAddressModel;
use App\Jobs\AutoCancelJob;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class OrderService extends BaseService
{
    /**
     * 发起支付请求
     * @param array $good_array     购买的商品
     * @param int|null $address_id       地址ID
     * @param int|null $coupon_id   使用的优惠券
     * @param string $remark        用户备注
     * @param int $is_from_cart     是否来源于购物车
     * @param array $order_extend    订单附加属性
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function orderPrepare(array $good_array, int $address_id = NULL, int $coupon_id = NULL, string $remark = '', int $is_from_cart = 0, array $order_extend = [])
    {
        /**
         * 查看用户信息和配置
         */
        $user_info      =   request()->post('api_user');
        $user_openid    =   $user_info['openid'];
        $user_id        =   $user_info['user_id'];

        /**
         * 获取用户地址信息
         */
        $address['user_id'] =   $user_id;
        if (is_null($address_id)) {
            $address['is_default']  =   1;
        } else {
            $address['id']      =   $address_id;
        }
        $address['is_delete']   =   UserAddressModel::NOT_DELETE;
        $address_info   =   UserAddressModel::where($address)->select(['user_name', 'tel_number', 'province', 'city', 'area', 'address', 'postal_code'])->first();
        if (empty($address_info)) {
            return [false, '请选择正确地址'];
        }
        $address_info   =   $address_info->toArray();
        $wechat_config  =   Config::get('wechat');

        /**
         * 计算商品价格
         */
        $total_result   =   $this->orderCalc($good_array, $coupon_id);
        $total_good     =   $total_result['total_good'];
        $coupon_price   =   $total_result['coupon_price'];
        $detail_good    =   $number_good    =   [];
        $gift_good      =   null;
        foreach ($good_array as $value) {
            /**
             * 是否有赠品
             */
            $gift_info  =   ProductGiftModel::where(['good_id' => $value['good_id'],'send_type' => ProductGiftModel::GOOD_GIFT, 'is_delete' => ProductGiftModel::NOT_DELETE, ['full_number', '<=', $value['good_number']]])->select(['id', 'good_id', 'send_id'])->first();
            if (!empty($gift_info)) {
                $gift_good  =   $gift_info['send_id'];
            }
            $number_good[$value['good_id']] =   ['spec_id' => $value['spec_id'], 'good_number' => $value['good_number']];
        }

        foreach ($total_good as $item) {
            $detail_good[]  =   $item['sku_code'];
        }
        $total_fee      =   $total_result['total_price'];

        /**
         * 获取店铺赠品
         */
        $shop_gift      =   ProductGiftModel::where(['shop_id' => 1,'send_type' => ProductGiftModel::SHOP_GIFT, 'is_delete' => ProductGiftModel::NOT_DELETE, ['condition', '<=', $total_fee]])->select(['id', 'good_id', 'shop_id', 'send_id'])->first();
        if (!empty($shop_gift)) {
            $gift_good  =   $shop_gift['send_id'];
        }

        /**
         * 设置附加信息
         */
        $order_attach   =   [];
        //盒子信息
        if (!empty($order_extend['box_unique'])) {
            $order_attach['box_unique'] =   $order_extend['box_unique'];
        }

        //直播间信息
        if (!empty($order_extend['live_unique'])) {
            $order_attach['live_unique'] =   $order_extend['live_unique'];
        }

        //邀请人信息
        if (!empty($order_extend['invite_unique'])) {
            $order_attach['invite_unique'] =   $order_extend['invite_unique'];
        }

        $now_time       =   Carbon::now()->timestamp;
        $order_prefix   =   $user_id . $now_time;
        $order_number   =   $order_prefix . (createRandomNumber(24  - strlen($order_prefix)));
        $pre_order['appid']     =   $wechat_config['appid'];
        $pre_order['mch_id']    =   $wechat_config['mch_id'];
        $pre_order['nonce_str'] =   Str::random(32);
        $pre_order['body']      =   '网虹城商品购物';
        $pre_order['detail']    =   json_encode($detail_good, JSON_UNESCAPED_UNICODE);
        $pre_order['attach']    =   json_encode($order_attach, JSON_UNESCAPED_UNICODE);
        $pre_order['total_fee'] =   1;      //$total_fee * 100
        $pre_order['openid']    =   $user_openid;
        $pre_order['spbill_create_ip']  =   request()->getClientIp();
        $pre_order['out_trade_no']      =   $order_number;
        $pre_order['time_start']        =   Carbon::now()->format('YmdHis');
        $pre_order['time_expire']       =   Carbon::parse("+2 hours")->format('YmdHis');
        $pre_order['notify_url']        =   $wechat_config['notify_url'];
        $pre_order['trade_type']        =   'JSAPI';
        $pre_order['sign']      =   wechatEncrypt($pre_order, $wechat_config['mch_key']);

        /**
         * 保存预下单记录
         */
        $pre_order_model    =   WechatOrderModel::create($pre_order);

        /**
         * 发起预下单请求
         */
        try {
            $query_client   =   new Client(['verify' => false, 'timeout' => 5]);
            $query_response =   $query_client->post('https://api.mch.weixin.qq.com/pay/unifiedorder', ['body' => xmlEncode($pre_order)]);
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
        $xml_data       =   $query_response->getBody()->getContents();
        $query_result   =   xmlObjectToArray(simplexml_load_string($xml_data, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS | LIBXML_NOERROR));

        /**
         * 预下单请求处理
         */
        if ($query_result['return_code'] == 'FAIL') {
            return [false, $query_result['return_msg']];
        } else {
            $pre_order_model->err_code      =   $query_result['err_code'] ?? '';
            $pre_order_model->err_code_desc =   $query_result['err_code_desc'] ?? '';
            if ($query_result['result_code'] == 'SUCCESS') {
                $pre_order_model->prepay_id =   $query_result['prepay_id'] ?? '';
                $pre_order_model->code_url  =   $query_result['code_url'] ?? '';
                $pre_order_model->save();

                /**
                 * 清除购物车数据
                 */
                if ($is_from_cart) {
                    (new CartService())->cartClear($good_array, $user_id);
                }

                /**
                 * 保存到订单表中，然后返回给前端接口
                 */
                DB::beginTransaction();

                try {
                    /**
                     * 插入主订单表
                     */
                    $normal_order['shop_id']   =    1;
                    $normal_order['user_id']   =    $user_id;
                    //查看box_unique的信息
                    if (!empty($order_attach['box_unique'])) {
                        $box_id     =   BoxModel::where(['unique_id' => $order_attach['box_unique']])->value('id') ?? 0;
                    }
                    //查看live_unique的信息
                    if (!empty($order_attach['live_unique'])) {
                        $live_id    =   LiveList::where(['HostId' => $order_attach['live_unique']])->whereIn('status', [1, 2])->orderBy('Id', 'desc')->value('Id') ?? 0;
                    }
                    //查看invite_unique的信息
                    if (!empty($order_attach['invite_unique'])) {
                        $share_id    =   UserModel::where(['unique_id' => $order_attach['invite_unique']])->value('uid') ?? 0;
                    }
                    $normal_order['box_id']    =    $box_id ?? 0;
                    $normal_order['live_id']   =    $live_id ?? 0;
                    $normal_order['share_id']  =    $share_id ?? 0;
                    $normal_order['coupon_id']      =    $coupon_id ?? 0;
                    $normal_order['order_no']       =    $order_number;
                    $normal_order['order_source']   =    1;
                    $normal_order['total_price']    =    $total_fee + $coupon_price;    //优惠前价格
                    $normal_order['update_price']   =    $total_fee;                    //优惠后价格
                    $normal_order['pay_price']      =    0;                             //用户实际支付价格
                    $normal_order['express_price']  =    0;
                    $normal_order['coupon_price']   =    $coupon_price;
                    $normal_order['discount']       =    100;
                    $normal_order['buyer_name']     =    $address_info['user_name'];
                    $normal_order['buyer_phone']    =    $address_info['tel_number'];
                    $normal_order['buyer_province'] =    $address_info['province'];
                    $normal_order['buyer_city']     =    $address_info['city'];
                    $normal_order['buyer_area']     =    $address_info['area'];
                    $normal_order['buyer_address']  =    $address_info['address'];
                    $normal_order['remark']         =    $remark;
                    $normal_order['gift_id']        =    is_null($gift_good) ? 0 : $gift_good;
                    $normal_order['created_at']     =    $normal_order['updated_at']   =   Carbon::now()->timestamp;
                    $insert_id  =   DB::table('mini_order')->insertGetId($normal_order);

                    $supply_good=   [];
                    foreach ($total_good as $item) {
                        $supply_good[$item['supply_id']][]  =   $item;
                    }
                    /**
                     * 插入供应商表
                     */
                    if (!empty($supply_good)) {
                        foreach ($supply_good as $key => $supply) {
                            $supply_count   =   $supply_total   =   0;
                            foreach ($supply as $single) {
                                $spec_good      =   array_pop($single['specs']);
                                $supply_count   +=  isset($number_good[$single['id']]) ? $number_good[$single['id']]['good_number'] : 0;
                                $supply_total   +=  isset($number_good[$single['id']]) ? $number_good[$single['id']]['good_number'] * (empty($spec_good) ? 0 : $spec_good['sell_price']) : 0;
                            }

                            $order_supply['order_id']   =   $insert_id;
                            $order_supply['uid']        =   $user_id;
                            $order_supply['voucher']    =   $coupon_price;
                            $order_supply['supply_id']  =   $key;
                            $order_supply['supply_total']=  $supply_total;
                            $order_supply['supply_count']=  $supply_count;
                            $order_supply['supply_price']=  0;
                            $order_supply['freight']    =   0;
                            $order_supply['exid']       =   -1;
                            $order_supply['express_etc']=   '';
                            $order_supply['msg']        =   '正常订单';
                            $order_supply['status']     =   1;
                            $order_supply['market']     =   $remark;
                            $order_supply['order_script']=  json_encode($supply, JSON_UNESCAPED_UNICODE);
                            $order_supply['created_at']  =  $order_supply['updated_at']   =   Carbon::now()->timestamp;

                            $order_id   =   DB::table('mini_order_supply')->insertGetId($order_supply);

                            /**
                             * 插入订单商品表
                             */
                            foreach ($supply as $single) {
                                $spec_good      =   array_pop($single['specs']);
                                $order_good['uid']      =   $user_id;
                                $order_good['order_id'] =   $insert_id;
                                $order_good['voucher']  =   $coupon_price;
                                $order_good['product_id']=  $single['id'];
                                $order_good['item_id']  =   isset($number_good[$single['id']]) ? $number_good[$single['id']]['spec_id'] : 0;;
                                $order_good['attr_pic'] =   empty($spec_good) ? '' : $spec_good['spec_pic'];
                                $order_good['msg']      =   '正常订单';
                                $order_good['status']   =   1;
                                $order_good['product_count']  =   isset($number_good[$single['id']]) ? $number_good[$single['id']]['good_number'] : 0;;
                                $order_good['product_price']  =   0;
                                $order_good['product_total']  =   empty($spec_good) ? 0 : $spec_good['sell_price'] * $order_good['product_count'];
                                $order_good['order_supply_id']=   $order_id;
                                $order_good['created_at']  =    $order_good['updated_at']   =   Carbon::now()->timestamp;

                                DB::table('mini_order_product')->insert($order_good);
                            }
                        }
                    }

                    DB::commit();
                    /**
                     * 放入自动取消列表
                     */
                    AutoCancelJob::dispatch(OrderModel::where(['id' => $insert_id])->select(['id', 'is_pay', 'order_status', 'order_no'])->first())->onQueue('auto_cancel');
                    //重新加密
                    $pay_param  =   [
                        'timeStamp' =>  $now_time,
                        'nonceStr'  =>  $pre_order['nonce_str'],
                        'signType'  =>  'MD5',
                        'package'   =>  'prepay_id=' . $pre_order_model->prepay_id,
                        'appId'     =>  $wechat_config['appid']
                    ];
                    $pay_param['paySign']   =   wechatEncrypt($pay_param, $wechat_config['mch_key']);
                    $pay_param['order_no']  =   $order_number;
                    return [true, $pay_param];
                } catch (\Exception $e) {
                    DB::rollBack();
                    return [false, $e->getMessage()];
                }

            } else {
                $pre_order_model->save();
                return [false, $query_result['err_code_desc'] ?? '请求错误'];
            }
        }
    }

    /**
     * 商品价格计算
     * @param array $good_array
     * @param int|null $coupon_id
     * @param int|null $user_id
     * @return array
     */
    public function orderCalc(array $good_array, int $coupon_id = NULL, int $user_id = NULL)
    {
        /**
         * 计算总价
         */
        $total_info    =   $this->orderGood($good_array);
        $total_price   =   $total_info['total_price'];
        $good_price    =   $total_info['good_price'];
        $shop_price    =   $total_info['shop_price'];

        /**
         * 计算优惠券价格
         */
        if ($coupon_id != NULL) {
            //获取用户信息
            if ($user_id == NULL) {
                $user_info  =   request()->post('api_user');
                $user_id    =   $user_info['user_id'];
            }
            /**
             * 判断是否优惠券是否有效
             */
            $active_coupon  =   UserCouponModel::query()->useful($user_id)->exists();
            if (!$active_coupon) {
                return ['total_good' => $total_info['total_good'], 'total_price' => round($total_price, 2), 'coupon_price' => 0];
            }

            /**
             * 判断优惠券是否能使用
             */
            $coupon_info    =   CouponModel::where(['id' => $coupon_id])->select(['id', 'name', 'desc', 'min_price', 'sub_price', 'type', 'discount', 'scene'])->first();
            if (!empty($coupon_info)) {
                switch ($coupon_info->scene) {
                    case CouponModel::PLATFORM_COUPON:
                        if ($total_price >= $coupon_info->min_price) {
                            //判断平台优惠券是折扣还是满减
                            if ($coupon_info->type == CouponModel::DECREASE_TYPE) {
                                $total_price    -=  $coupon_info->sub_price;
                            } else {
                                $total_price    *=  ($coupon_info->discount / 100);
                            }
                        }
                        break;

                    case CouponModel::SHOP_COUPON:
                        foreach ($coupon_info->connection as $value) {
                            if ($value['connect_type'] == CouponConnectionModel::SHOP_CONNECT && in_array($value['connect_id'], array_keys($shop_price)) && $coupon_info->min_price <= $shop_price[$value['connect_id']]) {
                                //判断店铺优惠券是折扣还是满减
                                if ($coupon_info->type == CouponModel::DECREASE_TYPE) {
                                    $total_price    -=  $coupon_info->sub_price;
                                } else {
                                    $total_price    *=  ($coupon_info->discount / 100);
                                }
                                break;
                            }
                        }
                        break;

                    case CouponModel::GOOD_COUPON:
                        foreach ($coupon_info->connection as $value) {
                            if ($value['connect_type'] == CouponConnectionModel::GOOD_CONNECT && in_array($value['connect_id'], array_keys($good_price)) && $coupon_info->min_price <= $good_price[$value['connect_id']]) {
                                //判断商品优惠券是折扣还是满减
                                if ($coupon_info->type == CouponModel::DECREASE_TYPE) {
                                    $total_price    -=  $coupon_info->sub_price;
                                } else {
                                    $total_price    *=  ($coupon_info->discount / 100);
                                }
                                break;
                            }
                        }
                        break;
                }
            }

        }
        return ['total_good' => $total_info['total_good'], 'total_price' => sprintf('%.2f', $total_price), 'coupon_price' => sprintf('%.2f', $total_info['total_price'] - $total_price)];
    }

    /**
     * 结算列表页商品详情
     * @param array $good_array
     * @param int|null $address_id
     * @return array
     */
    public function orderSettle(array $good_array, int $address_id = NULL)
    {
        $user_info = request()->post('api_user');

        $limit_service  =   new LimitService();
        /**
         * 获取结算商品
         */
        $total_price    =   0;
        $gift_good      =   null;
        $total_good     =   $can_use_coupon   =   $cannot_use_coupon    =   $good_coupon    =   $shop_coupon   =   [];
        foreach ($good_array as $item) {
            $single_good    =   ProductModel::with([
                                    'specs' =>  function ($query) use ($item) {
                                        $query->where(['id' => $item['spec_id']])->select(['id', 'product_id', 'attr_list', 'sell_price', 'original_price', 'stock', 'spec_pic', 'sku_code']);
                                    }
                                ])->where(['id' => $item['good_id']])->sell()->select(['id', 'name', 'sell_price', 'stock', 'cover_pic', 'shop_id'])->first();
            if (empty($single_good)) {
                continue;
            }

            /**
             * 判断是否显示折扣商品
             */
            [$is_limit, $limit_discount]    =   $limit_service->checkLimit($item['good_id']);

            if (!empty($single_good->specs)) {
                foreach ($single_good->specs as &$spec_info) {
                    /**
                     * 是否有赠品
                     */
                    $gift_info  =   ProductGiftModel::where(['good_id' => $item['good_id'],'send_type' => ProductGiftModel::GOOD_GIFT, 'is_delete' => ProductGiftModel::NOT_DELETE, ['full_number', '<=', $item['good_number']]])->select(['id', 'good_id', 'send_id'])->first();
                    if (!empty($gift_info)) {
                        $gift_good  =   $gift_info['send_id'];
                    }
                    $spec_info->attr_value  =   !empty($spec_info->attr_list) ? array_values(json_decode($spec_info->attr_list, true)) : [];
                    if ($spec_info->id == $item['spec_id']) {
                        $spec_price     =   $item['good_number'] * (float) ($is_limit ? round($spec_info->sell_price * $limit_discount['discount'] / 10, 2) : $spec_info->sell_price);
                        $total_price    +=  $spec_price;
                        $good_coupon[$item['good_id']]  =   isset($good_coupon[$item['good_id']]) ? $good_coupon[$item['good_id']] + $spec_price : $spec_price;
                        $shop_coupon[$single_good->shop_id]  =   isset($shop_coupon[$single_good->shop_id]) ? $shop_coupon[$single_good->shop_id] + $spec_price : $spec_price;
                    }
                }
            }

            $single_good['good_number'] =   $item['good_number'];
            $total_good[]   =   $single_good;
        }

        /**
         * 获取商品可使用的优惠券
         */
        $coupon_list    =   UserCouponModel::query()->with([
                                'coupon' => function ($query) use($good_coupon, $shop_coupon) {         //优惠券信息     选择使用场景的优惠券
                                    $query->whereIn('scene', [CouponModel::SHOP_COUPON, CouponModel::GOOD_COUPON])->with([
                                        'connection' => function ($query) use($good_coupon, $shop_coupon){      //优惠券关联信息，选择指定商品的优惠券 或者 指定店铺的优惠券
                                            $query->where(['connect_type' => CouponConnectionModel::GOOD_CONNECT])->whereIn('connect_id', array_keys($good_coupon) ?? [0])->orWhere(function ($query) use ($shop_coupon){
                                                $query->where(['connect_type' => CouponConnectionModel::SHOP_CONNECT])->whereIn('connect_id', array_keys($shop_coupon) ?? [0]);
                                            })->select(['id', 'connect_type', 'connect_id', 'coupon_id']);
                                        }
                                    ])->orWhere(['scene' => CouponModel::PLATFORM_COUPON])->select(['id', 'name', 'desc', 'min_price', 'sub_price', 'type', 'discount', 'scene']);
                                }
                            ])->useful($user_info['user_id'])->select(['id', 'user_id', 'coupon_id', 'fetch_time', 'begin_time', 'end_time'])->get()->each(function (&$item) {
                                $item->fetch_time   =   Carbon::createFromTimestamp($item->fetch_time)->toDateTimeString();
                                $item->begin_time   =   Carbon::createFromTimestamp($item->begin_time)->toDateTimeString();
                                $item->end_time     =   Carbon::createFromTimestamp($item->end_time)->toDateTimeString();
                            });

        if (!$coupon_list->isEmpty()) {
            foreach ($coupon_list->toArray() as $item) {
                if (empty($item['coupon'])) {
                    continue;
                }
                $use_flag   =   false;
                /**
                 * 判断使用场景
                 */
                switch ($item['coupon']['scene']) {
                    case CouponModel::PLATFORM_COUPON:          //平台优惠券 总价格大于最低使用价格才可以使用
                        if ($item['coupon']['min_price'] <= $total_price) {
                            $use_flag   =   true;
                        }
                        break;

                    case CouponModel::SHOP_COUPON:              //指定店铺优惠券  该商品总价格大于最低使用价格才可以使用
                        if (!empty($shop_coupon)) {
                            foreach ($item['coupon']['connection'] as $value) {
                                if ($value['connect_type'] == CouponConnectionModel::SHOP_CONNECT && in_array($value['connect_id'], array_keys($shop_coupon)) && $item['coupon']['min_price'] <= $shop_coupon[$value['connect_id']]) {
                                    $use_flag   =   true;
                                    break;
                                }
                            }
                        }
                        break;

                    case CouponModel::GOOD_COUPON:              //指定商品优惠券  该商品总价格大于最低使用价格才可以使用
                        if (!empty($good_coupon)) {
                            foreach ($item['coupon']['connection'] as $value) {
                                if ($value['connect_type'] == CouponConnectionModel::GOOD_CONNECT && in_array($value['connect_id'], array_keys($good_coupon)) && $item['coupon']['min_price'] <= $good_coupon[$value['connect_id']]) {
                                    $use_flag   =   true;
                                    break;
                                }
                            }
                        }
                        break;
                }

                $item['coupon']['fetch_time']   =   $item['fetch_time'];
                $item['coupon']['begin_time']   =   $item['begin_time'];
                $item['coupon']['end_time']     =   $item['end_time'];
                if ($use_flag) {
                    $can_use_coupon[]   =   $item['coupon'];
                } else {
                    $cannot_use_coupon[]=   $item['coupon'];
                }
            }
        }

        $user_address['user_id']    =   $user_info['user_id'];
        $user_address['is_delete']  =   UserAddressModel::NOT_DELETE;

        if (is_null($address_id)) {
            $user_address['is_default']    =   1;
        } else {
            $user_address['id']     =   $address_id;
        }

        /**
         * 获取用户指定地址
         */
        $default_address    =   UserAddressModel::where($user_address)->select(['id', 'user_name', 'tel_number', 'province', 'city', 'area', 'address'])->first();

        /**
         * 获取店铺赠品
         */
        $shop_gift      =   ProductGiftModel::where(['shop_id' => 1,'send_type' => ProductGiftModel::SHOP_GIFT, 'is_delete' => ProductGiftModel::NOT_DELETE, ['condition', '<=', $total_price]])->select(['id', 'good_id', 'shop_id', 'send_id'])->first();
        if (!empty($shop_gift)) {
            $gift_good  =   $shop_gift['send_id'];
        }

        $send_gift      =   is_null($gift_good) ? [] : ProductModel::where(['id' => $gift_good])->select(['id', 'unique_id', 'name', 'cover_pic'])->first();
        return [true, [
            'good_list'     =>  $total_good,
            'good_price'    =>  sprintf('%.2f', $total_price),
            'default_address'=> empty($default_address) ? [] : $default_address->toArray(),

            'can_use_coupon'    =>  $can_use_coupon,
            'cannot_use_coupon' =>  $cannot_use_coupon,
            'gift_info' =>  $send_gift
        ]];
    }

    /**
     * 获取商品列表总价格
     * @param array $good_array
     * @return array
     */
    protected function orderGood(array $good_array)
    {
        $total_price    =   0.00;
        $total_good     =   $good_price =   $shop_price =   [];
        foreach ($good_array as $item) {
            $single_good    =   ProductModel::with([
                'specs' =>  function ($query) use ($item) {
                    $query->where(['id' => $item['spec_id']])->select(['id', 'product_id', 'attr_list', 'sell_price', 'original_price', 'stock', 'spec_pic', 'sku_code']);
                }
            ])->where(['id' => $item['good_id']])->sell()->select(['id', 'name', 'sell_price', 'stock', 'cover_pic', 'shop_id', 'sku_code', 'supply_id'])->first();
            if (empty($single_good)) {
                continue;
            }

            if (!empty($single_good->specs)) {
                foreach ($single_good->specs as &$spec_info) {
                    $spec_info->attr_value  =   !empty($spec_info->attr_list) ? array_values(json_decode($spec_info->attr_list, true)) : [];
                    if ($spec_info->id == $item['spec_id']) {
                        $spec_price     =   $item['good_number'] * $spec_info->sell_price;
                        $total_price    +=  $spec_price;
                        $good_price[$item['good_id']]       =   isset($good_price[$item['good_id']]) ? $good_price[$item['good_id']] + $spec_price : $spec_price;
                        $shop_price[$single_good->shop_id]  =   isset($shop_price[$single_good->shop_id]) ? $shop_price[$single_good->shop_id] + $spec_price : $spec_price;
                    }
                }
            }

            $total_good[]   =   $single_good->toArray();
        }

        return ['total_price' => round($total_price, 2), 'total_good' => $total_good, 'good_price' => $good_price, 'shop_price' => $shop_price];
    }

}
